package com.allwees.core.common.jexl;

import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.apache.commons.jexl3.internal.Engine;
import org.springframework.util.CollectionUtils;

import java.util.Map;

public class JexlEngine {
    private static final org.apache.commons.jexl3.JexlEngine ENGINE = Holder.ENGINE;

    private static class Holder {
        static org.apache.commons.jexl3.JexlEngine ENGINE = new Engine();
    }

    public static Object execute(String jexlExpression, Map<String, Object> map) {
        JexlExpression expression = ENGINE.createExpression(jexlExpression);
        JexlContext context = new MapContext();
        if (!CollectionUtils.isEmpty(map)) {
            map.forEach(context::set);
        }
        return expression.evaluate(context);
    }
}
